//
//  LJTextView.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/27.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit

class LJTextView: UITextView {
    
    var placeholder: String? {
        didSet{
            placeholderLabel.text = placeholder
            placeholderLabel.sizeToFit()
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        prepareUI()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI() {
        addSubview(placeholderLabel)
        
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        self.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    }
    
    // MARK: - 通知回调方法
    @objc private func textDidChange() {
        placeholderLabel.hidden = hasText()
    }
    
    // MARK: - 懒加载
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
}